<?php

namespace app\rongcui\controller;

use app\rongcui\model\AreasModel;
use app\rongcui\model\CustomerNatureModel;
use app\rongcui\model\RongcuiFollowModel;
use app\rongcui\model\RongcuiIndustryCateModel;
use app\rongcui\model\RongcuiPotentialCustomerModel;
use app\resource\model\CurrencyModel;
use cmf\controller\AdminBaseController;

class PotentialCustomerController extends AdminBaseController
{
    protected $cate;
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->cate = [
            'other',
            'bxjj',
            'qgbxdl',
            'qybxdl',
            'rzdb',
            'xed',
            'ddh',
        ];
        $this->assign('cate',$this->cate);
    }

    function index()
    {
        $potentialCustomerModel = new RongcuiPotentialCustomerModel();

        $where = [
            'lock_uid' => ['eq',0],
            'potential.is_del' => 0
        ];
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['company|corporation|phone|registered_capital'] = ['like', "%$keyword%"];
//            $where['company|corporation|address|email|phone|remark|scope'] = ['like', "%$keyword%"];
        }

        $areasModel = new AreasModel();
        $areas = $areasModel->where([
            'parentid' => 0,
        ])->field('areaid,name')->select();

        if (input('cite')) {
            $cite = input('cite');
            $cite = $areasModel->where([
                'areaid' => $cite
            ])->find();
            if($cite) {
                $where['address'] = ['like', "%{$cite['name']}%"];
            }
        }else if (input('sheng')) {
            $sheng = input('sheng');
            $like = [];
            foreach ($areas as $area) {
                if($area['areaid'] == $sheng) {
                    $like[] = "%{$area['name']}%";
                }
            }
            if(!in_array($sheng,[
                '110000',
                '120000',
                '310000',
                '500000',
                '810000',
                '820000',
            ])) {
                $cites = $areasModel
                    ->where([
                        'parentid' => $sheng
                    ])
                    ->select();
                foreach ($cites as $cite) {
                    $like[] = "%{$cite['name']}%";
                }
            }
            $where['address'] = ['like', $like,'or'];
        }


        $lists = $potentialCustomerModel
            ->alias('potential')
            ->join('__CURRENCY__ currency', 'potential.currency = currency.id')
            ->field('potential.*,currency.name cname')
            ->where($where)
            ->order('id desc')
            ->paginate();

        $where_r = input();
        $lists->appends($where_r);
        $page = $lists->render();

        $this->assign('areas', $areas);
        $this->assign('where_r', $where_r);
        $this->assign('lists', $lists);
        $this->assign('page', $page);
        return $this->fetch();
    }

    function bxjj() {
        $where= [];
        $where['cate_id'] = 1;
        $this->assign('cate_id',1);
        $this->assign('title','保险经纪');
        return $this->ziyuan($where);
    }

    function qgbxdl() {
        $where= [];
        $where['cate_id'] = 2;
        $this->assign('cate_id',2);
        $this->assign('title','全国保险代理');
        return $this->ziyuan($where);
    }

    function qybxdl() {
        $where= [];
        $where['cate_id'] = 3;
        $this->assign('cate_id',3);
        $this->assign('title','区域保险代理');
        return $this->ziyuan($where);
    }

    function rzdb() {
        $where= [];
        $where['cate_id'] = 4;
        $this->assign('cate_id',4);
        $this->assign('title','融资担保');
        return $this->ziyuan($where);
    }

    function xed() {
        $where= [];
        $where['cate_id'] = 5;
        $this->assign('cate_id',5);
        $this->assign('title','小额贷');
        return $this->ziyuan($where);
    }

    function ddh() {
        $where= [];
        $where['cate_id'] = 6;
        $this->assign('cate_id',6);
        $this->assign('title','典当行');
        return $this->ziyuan($where);
    }

    function other() {
        $where= [];
        $where['cate_id'] = 7;
        $this->assign('cate_id',7);
        $this->assign('title','其他');
        return $this->ziyuan($where);
    }

    protected function ziyuan($where = [])
    {
        $potentialCustomerModel = new RongcuiPotentialCustomerModel();

        $where['lock_uid'] = ['eq',0];
        $where['potential.is_del'] = 0;

        if (input('keyword')) {
            $keyword = input('keyword');
            $where['company|corporation|phone|registered_capital|address|user_nickname'] = ['like', "%$keyword%"];
//            $where['company|corporation|address|email|phone|remark|scope'] = ['like', "%$keyword%"];
        }
        if (input('attorn')) {
            $where['attorn'] = input('attorn');
        }
        if (input('min_registered_capital')) {
            $where['registered_capital'] = ['egt',input('min_registered_capital')];
        }
        if (input('max_registered_capital')) {
            if(isset($where['registered_capital'])) {
                $where['registered_capital'] = ['between',[input('min_registered_capital'),input('max_registered_capital')]];
            }else{
                $where['registered_capital'] = ['elt',input('max_registered_capital')];
            }
        }
        if (input('regtime')) {
            $regtime = input('regtime');
            switch ($regtime) {
                case 1:
                    $where['regtime'] = ['egt',strtotime('-1 year')];
                    break;
                case 2:
                    $where['regtime'] = ['between',[strtotime('-2 year'),strtotime('-1 year')]];
                    break;
                case 3:
                    $where['regtime'] = ['between',[strtotime('-3 year'),strtotime('-2 year')]];
                    break;
                case 4:
                    $where['regtime'] = ['between',[strtotime('-5 year'),strtotime('-3 year')]];
                    break;
                case 5:
                    $where['regtime'] = ['between',[strtotime('-10 year'),strtotime('-5 year')]];
                    break;
                case 6:
                    $where['regtime'] = ['elt',strtotime('-10 year')];
                    break;
            }
        }

        $areasModel = new AreasModel();
        $areas = $areasModel->where([
            'parentid' => 0,
        ])->field('areaid,name')->select();

        if (input('cite')) {
            $cite = input('cite');
            $cite = $areasModel->where([
                'areaid' => $cite
            ])->find();
            if($cite) {
                $where['address'] = ['like', "%{$cite['name']}%"];
            }
        }else if (input('sheng')) {
            $sheng = input('sheng');
            $like = [];
            foreach ($areas as $area) {
                if($area['areaid'] == $sheng) {
                    $like[] = "%{$area['name']}%";
                }
            }
            if(!in_array($sheng,[
                '110000',
                '120000',
                '310000',
                '500000',
                '810000',
                '820000',
            ])) {
                $cites = $areasModel
                    ->where([
                        'parentid' => $sheng
                    ])
                    ->select();
                foreach ($cites as $cite) {
                    $like[] = "%{$cite['name']}%";
                }
            }
            $where['address'] = ['like', $like,'or'];
        }


        $lists = $potentialCustomerModel
            ->alias('potential')
            ->join('__CURRENCY__ currency', 'potential.currency = currency.id')
            ->join('__USER__ user','potential.uid = user.id')
            ->field('potential.*,currency.name cname,user.user_nickname')
            ->where($where)
            ->order('id desc')
            ->paginate();

        $where_r = input();
        $lists->appends($where_r);
        $page = $lists->render();

        $customerNatureModel = new CustomerNatureModel();
        $attorn = $customerNatureModel->where([
            'type' => 9,
            'is_del' => 0
        ])->field('id,name')->select();

        $rongcuiIndustryCateModel = new RongcuiIndustryCateModel();
        $cates = $rongcuiIndustryCateModel
            ->where([
                'is_del' => 0
            ])->order('list_order')->select();

        $status = 0;
        foreach ($cates as $cate) {
            if($cate['id'] == $where['cate_id']) {
                $status = $cate['status'];
            }
        }

        $this->assign('attorn', $attorn);
        $this->assign('cates', $cates);
        $this->assign('areas', $areas);
        $this->assign('status', $status);
        $this->assign('where_r', $where_r);
        $this->assign('lists', $lists);
        $this->assign('page', $page);
        return $this->fetch('ziyuan');
    }

    function import_list()
    {
        $lists = db('import_list')
            ->alias('importlist')
            ->join('__USER__ user', 'importlist.uid = user.id')
            ->field('importlist.*,user.user_nickname')
            ->order('importlist.id desc')
            ->paginate();

        $this->assign('lists', $lists);
        $this->assign('page', $lists->render());
        return $this->fetch();
    }

    function upfile()
    {
        $file_name = $this->request->param('file_name');
        $file = 'upload/' . $file_name;
        if (!$file) {
            $this->error('文件上传失败');
        }
        if (!file_exists($file)) {
            $this->error('文件上传失败');
        }

        try {
            $objRead = new \PHPExcel_Reader_Excel2007();   //建立reader对象
            if (!$objRead->canRead($file)) {
                $objRead = new \PHPExcel_Reader_Excel5();
                if (!$objRead->canRead($file)) {
                    $objRead = new \PHPExcel_Reader_CSV();
                    if (!$objRead->canRead($file)) {
                        $this->error('文件读取失败');
                    }
                }
            }
        } catch (\Exception $e) {
            $this->error('文件读取失败');
        }
        $id = db('import_list')->insertGetId([
            'filename' => $file_name,
            'create_time' => time(),
            'status' => 0,
            'uid' => cmf_get_current_admin_id()
        ]);
        pclose(popen("php ../think import_file {$id} &", 'r'));
        $this->success('上传成功');
    }

    public function edit()
    {
        $id = $this->request->param('id',0,'intval');
        $remark = $this->request->param('remark');
        db('potential_customer')->where([
            'id' => $id
        ])->update([
            'remark' => $remark
        ]);
        $this->success('保存成功');
    }

    public function add(){
        if($this->request->isPost()) {
            $arrData = $this->request->param();
            $arrData['uid'] = cmf_get_current_admin_id();

            $rongcuiPotentialCustomerModel = new RongcuiPotentialCustomerModel();
            $flag = $rongcuiPotentialCustomerModel->allowField(true)->validate([
                'company' => 'require|unique:rongcui_potential_customer',
            ],[
                'company.require' => '公司名称不能为空！',
                'company.unique' => '公司名称不能重复！',
            ])->save($arrData);
            if($flag !== false) {
                $this->success('添加成功！',url($this->cate[$arrData['cate_id']]));
            }else{
                $this->error($rongcuiPotentialCustomerModel->getError());
            }
        }
        $cate_id = $this->request->param('cate_id',0,'intval');
        $currency = new CurrencyModel();
        $defCurrency = $currency->where(['id' => 1])->find();

        $customerNatureModel = new CustomerNatureModel();
        $lists = $customerNatureModel->where([
            'type' => 9
        ])->order('list_order,id')->select();


        $rongcuiIndustryCateModel = new RongcuiIndustryCateModel();
        $cates = $rongcuiIndustryCateModel
            ->where([
                'is_del' => 0,
                'status' => 1
            ])->order('list_order')->select();

        $this->assign('defCurrency', $defCurrency);
        $this->assign('lists', $lists);
        $this->assign('cates', $cates);
        $this->assign('cate_id', $cate_id);
        return $this->fetch();
    }

    function change() {
        $cate_id = $this->request->param('cate_id',0,'intval');
        $id = $this->request->param('id',0,'intval');

        $potentialCustomerModel = new RongcuiPotentialCustomerModel();
        $potentialCustomerModel->where([
            'id' => $id
        ])->setField('cate_id',$cate_id);
        $this->success('设置成功！');
    }

    function show() {
        $pid = $this->request->param('pid', 0, 'intval');
        if (!$pid) {
            $this->error('非法访问');
        }

        $followModel = new RongcuiFollowModel();
        $where = ['type' => 3, 'pid' => $pid];
        $lists = $followModel
            ->alias('follow')
            ->join('__USER__ user', 'follow.uid = user.id')
            ->field('follow.*,user.user_nickname as uname')
            ->where($where)
            ->order(['id desc'])
            ->paginate(10);
        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('page', $page);
        $this->assign('pid', $pid);
        return $this->fetch();
    }
}